<template>
  <div class="wrap">
    <aside id="dag-stencil" class="panel-left">
      <StencilTree v-if="enabled"></StencilTree>
    </aside>
    <main class="panel-center">
      <div class="tool-bar">
        <ToolBar
          v-if="enabled"
          :current-select="currentSelect"
          @saveStrategy="handleSaveDag"
        ></ToolBar>
      </div>
      <div class="x6-graph-box">
        <div id="x6-graph-container" class="x6-graph-container"></div>
      </div>
    </main>
    <aside class="panel-right">
      <header class="base-header-title">模块结果</header>
      <div v-if="enabled" class="right-content">
        <VisualizedResult :base-url="baseUrl" :status="status" :cell-name.sync="cellName"/>
      </div>
    </aside>
    <ContextMenu v-if="enabled"></ContextMenu>

    <el-dialog title="参数设置" :visible.sync="paramsDialogVisible" @close='handleCancelDialog'>
      <EditOrderForm
        v-if="currentSelect === 'pipeline'"
        ref="orderForm"
        :form-data="cellData"
        @updateCellData="setNodeInfo"
      >
      </EditOrderForm>
      <EditOrderForm
        v-else
        ref="orderForm"
        :form-data="cellData"
        @updateCellData="setNodeInfo"
      >
      </EditOrderForm>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleCancelDialog">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="保存当前流程" :visible.sync="saveDialogVisible">
      <el-form :model="flowData">
        <el-form-item label="流程名称" label-width="80px">
          <el-input placeholder="请输入流程名称" v-model="flowData.title"></el-input>
        </el-form-item>
        <el-form-item label="流程描述" label-width="80px">
          <el-input placeholder="请输入流程描述" v-model="flowData.description"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="uploadDag">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import DagGraph from './graph'
import ToolBar from './components/ToolBar'
import ContextMenu from './components/ContextMenu'
import EditOrderForm from './components/EditOrderForm'
import StencilTree from './components/StencilTree'
import VisualizedResult from './components/VisualizedResult'
import { formData } from './const/data'
import { baseURL } from '@/config/baseConfig'
import { translate } from '@/views/process/dag/DagEdit/const/translate'
import { createObj } from '../../processManagement/api'

let graph = null
export default {
  name: 'EditorDag',
  components: {
    StencilTree,
    ToolBar,
    ContextMenu,
    EditOrderForm,
    VisualizedResult
  },
  data () {
    return {
      enabled: false,
      activeName: 'nodeData',
      currentSelect: 'none', // none、edge、pipeline、fork
      currentCell: null,
      cellData: {},
      graphData: null,
      paramsDialogVisible: false,
      saveDialogVisible: false,
      cellName: '',
      baseUrl: [baseURL + 'media/temp/DAG_instruction.png'],
      status: 'info',
      flowData: {
        title: '',
        description: '',
        data: {}
      },
      currentNodeId: ''
    }
  },
  created () {
    this.graphData = this.$route.params.graph
    this.updateWsDataTimer = setInterval(() => {
      this.updateWsData()
    }, 2000)
  },
  mounted () {
    this.initDagGraph()
    this.initGraphStart()
    this.$websocket.initWebSocket(graph)
    this.loadGraphData(this.graphData)
  },
  beforeDestroy () {
    DagGraph.destroy()
    this.$websocket.close()
    clearInterval(this.updateWsDataTimer)
  },
  methods: {
    // 初始化x6图编辑引擎
    initDagGraph () {
      graph = DagGraph.init('#x6-graph-container')
      this.enabled = true
      this.initClickEvent()
      // 装载流程图数据
    },
    // 初始化开始节点
    initGraphStart () {
      graph.clearCells()
      graph.center() // 内容居中
      graph.zoomTo(1) // 缩放比例
      // eslint-disable-next-line camelcase
      const start_node = graph.createNode({
        shape: 'start',
        x: 100,
        y: 50,
        data: formData.start
      })
      graph.addNode(start_node)
    },
    // 初始化点击事件
    async initClickEvent () {
      graph.on('blank:click', async () => {
        if (this.currentCell !== null) {
          this.clearData()
        }
      })
      graph.on('cell:dblclick', ({ cell }) => {
        const isNode = cell.isNode()
        this.clearData()
        if (isNode) {
          this.getNodeInfo(cell)
        }
      })
      graph.on('cell:click', ({ cell }) => {
        this.clearData()
        console.log('click:', cell)
        this.cellName = cell.data.name.label
        console.log('click test: ', this.$websocket.getWsData())
        const isNode = cell.isNode()
        if (isNode) {
          this.currentCell = cell
        }
        if (this.$websocket.getWsData()[cell.id]) {
          // this.baseUrl = baseURL + this.$websocket.getWsData()[cell.id].img
          this.baseUrl = this.$websocket.getWsData()[cell.id].img.map((item) => baseURL + item)
          this.status = this.$websocket.getWsData()[cell.id].status
        } else if (Object.keys(this.$websocket.getWsData()).length !== 0 && !this.$websocket.getWsData()[cell.id]) {
          this.baseUrl = [baseURL + 'media/temp/DAG_instruction.png']
          this.status = 'danger'
        } else {
          this.baseUrl = [baseURL + 'media/temp/DAG_instruction.png']
          this.status = 'info'
        }

        if (cell.shape === 'end' && this.$websocket.getWsData()[cell.id]) {
          const info = this.$websocket.getWsData()[cell.id].info
          for (const i in info) {
            cell.data.params[i] = { label: translate[i], value: info[i] }
          }
        }
      })
      graph.on('edge:connected', ({ isNew, edge }) => {
        if (isNew) {
          const source = edge.getSourceCell()
          const target = edge.getTargetCell()
          console.log('source:', source)
          console.log('target:', target.data.name.value)
          if (target.data.name.value === 'fork') {
            for (const i in source.data.results) {
              target.data.params.condition.options.push(source.data.results[i].label)
            }
          }
        }
      })
    },
    // 获取被选中节点的数据
    getNodeInfo (cell) {
      this.currentSelect = cell.shape
      this.currentCell = cell
      Object.assign(this.cellData, cell.getData())
      // console.log('getNodeInfo:', this.cellData)
      const nodeAttrs = cell.getAttrs()
      this.cellData.name.label = nodeAttrs?.label?.text
      this.paramsDialogVisible = true
    },
    // 清空选中节点数据
    clearData () {
      const data = this.$options.data()
      this.cellData = data.config
      this.currentCell = null
      this.currentSelect = 'none'
      this.cellData = data.cellData
    },
    // 设置当前选中节点的数据
    setNodeInfo (val) {
      this.cellData = val
      if (val?.name) {
        const attr = {
          label: {
            text: this.cellData.name.label
          }
        }
        this.currentCell.setAttrs(attr)
      }
      const options = {
        silent: true,
        overwrite: true
      }
      this.currentCell.setData(this.cellData, options)
    },
    // 保存dag图数据
    handleSaveDag () {
      this.saveDialogVisible = true
      this.graphData = graph.toJSON()
      this.flowData.data = this.graphData
    },
    uploadDag () {
      this.saveDialogVisible = false
      createObj(this.flowData).then(res => {
        console.log('res:', res)
      })
    },
    backPage () {
      this.$router.go(-1)
    },
    handleCancelDialog () {
      this.paramsDialogVisible = false
      graph.unselect(this.currentCell)
      this.clearData()
    },
    loadGraphData (graphData) {
      graph.fromJSON(graphData)
    },
    updateWsData () {
      if (this.currentCell !== null) {
        this.baseUrl = this.$websocket.getWsData()[this.currentCell?.id]?.img.map((item) => baseURL + item)
      }
      console.log('updateWsData:', this.$websocket.getWsData()[this.currentCell?.id], this.currentCell)
    }
  }
}
</script>

<style lang="scss">
@import "./index.scss";
</style>
